package net.didactylos.helpline.data;

import java.util.Iterator;
import java.util.List;

import net.sourceforge.stripes.util.Log;

import org.hibernate.Session;

public class ConversationManager
{
	private static final Log log = Log.getInstance(ConversationManager.class);
	
	private Session session;
	
	public ConversationManager(Session session)
	{
		super();
		this.session = session;
	}

	/**
	 * Finds a conversation that a message should belong to, and
	 * appends it. Creates a new conversation if none is suitable.
	 */
	public Conversation append(Message message)
	{
		Conversation conversation = null;
		Contact contact = null;

		if (message.author instanceof Contact)
		{
			contact = (Contact)message.author;
		}
		
		// Look up contact using From field
		// not found
		//    new contact
		//    new conversation
		// found - we have a contact
		//    Try In-Reply-To
		//       found - use conversation
		//       not found
		//          Look up latest conversation
		
		List<Conversation> conversations = contact.getConversations();
		if (conversations != null)
		{
			for (Iterator<Conversation> iterator = conversations.iterator(); iterator.hasNext();)
			{
				Conversation c = iterator.next();
				if (c.getClosed() != true)
				{
					conversation = c;
					break;
				}
			}
		}
		if (conversation == null)
		{
			conversation = new Conversation();
			conversation.setContact(contact);
			session.save(conversation);
		}
		//             not found
		//             Too old
		//             Subject line change
		//                new conversation
		//             Otherwise
		//                use found conversation
		
		message.setConversation(conversation);

		return conversation;
	}
	
	// detach
	// merge
	
	// changeContact
}
